﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using kwzx.Data;
using kwzx.Common;
using System.IO;
using System.Threading;

namespace kwzx
{
    /// <summary>
    /// 此界面只能运行在服务端，客户端因为要ftp下载，然后把裁剪的图片上传到服务器端较麻烦
    /// </summary>
    public partial class frmScmDataSyn : Form
    {
        public frmScmDataSyn()
        {
            InitializeComponent();
        }


        DataSet1TableAdapters.T_BMTableAdapter bm = new DataSet1TableAdapters.T_BMTableAdapter();
        DataSet1TableAdapters.T_GROUPTableAdapter group = new DataSet1TableAdapters.T_GROUPTableAdapter();
        DataSet1TableAdapters.V_jg_bmTableAdapter vjgbm = new DataSet1TableAdapters.V_jg_bmTableAdapter();





        private void SetTextMessage(int ipos)
        {


            this.Invoke((MethodInvoker)delegate
            {
                this.labProgress.Text = ipos.ToString() + "/100";
                this.progressBar1.Value = Convert.ToInt32(ipos);
                if (ipos == 100)
                {
                    this.labProgress.Text = "导入完成";
                }
            });


        }


        private void frmScmDataSyn_Load(object sender, EventArgs e)
        {
            InitTree();
        }
        private void btnSynDept_Click(object sender, EventArgs e)
        {

            new Thread(new ThreadStart(delegate
            {
                HXYKTEntities db = new HXYKTEntities();
                var bm = db.T_BM.ToList().OrderBy(a => a.SXH);
                int id = 1;

                try
                {
                    foreach (var item in bm.ToList())
                    {
                        int ipos = 100 * id / bm.ToArray().Length;

                        SetTextMessage(ipos);
                        id++;
                        CallProc call = new CallProc();
                        if (item.GRPUP_ID != 83)
                        {
                            call.DeptEx(item.DEPT_id.ToString(), 1001, item.BMMC.ToString(), false);
                        }
                        else
                        {
                            if (item.SJBM == 0)
                            {
                                call.DeptEx(item.DEPT_id.ToString(), int.Parse(item.GRPUP_ID.ToString()), item.BMMC.ToString(), true);
                            }
                            else
                            {
                                call.DeptEx(item.DEPT_id.ToString(), int.Parse(item.SJBM.ToString()), item.BMMC.ToString(), true);
                            }

                        }
                    }
                }
                catch (Exception ex)
                {
                    string log = string.Format("同步部门失败,请联系软件维护人员");
                    this.rtFailInfo.Text += log + ex.ToString();
                    Log.WriteInfo(log);

                }

                rtFailInfo.Invoke(new Action(() =>
                {
                    rtFailInfo.Text = "同步部门信息成功";
                }));


            })).Start();



        }

        private void btnSynPerson_Click(object sender, EventArgs e)
        {
            if (treeView1.SelectedNode.Nodes != null)
            {

                int groupID = int.Parse(treeView1.SelectedNode.Tag.ToString());
                string nodeType = treeView1.SelectedNode.ToolTipText;
                string name = treeView1.SelectedNode.Text;
                HXYKTEntities db = new HXYKTEntities();
                List<View_UserInfo> user = new List<View_UserInfo>();
                this.rtFailInfo.Text = "";
                if (nodeType == "jg")
                {

                    if (groupID == -1)
                    {
                        user = db.View_UserInfo.ToList().Where(a => a.GRPUP_ID == 83).Where(a => a.DEPT_id != 320).ToList();
                        this.rtFailInfo.Text = "正在同步" + name + "所有部门下人员信息" + Environment.NewLine;
                    }
                    else if (groupID == 0)
                    {
                        user = db.View_UserInfo.ToList().Where(a => a.GRPUP_ID != 83).Where(a => a.DEPT_id != 320).ToList();
                        this.rtFailInfo.Text = "正在同步" + name + "所有部门下人员信息" + Environment.NewLine;
                    }
                    else
                    {
                        this.rtFailInfo.Text = "正在同步" + name + "下人员信息" + Environment.NewLine;
                        user = db.View_UserInfo.ToList().Where(a => a.GRPUP_ID == groupID).Where(a => a.DEPT_id != 320).ToList();
                    }
                }
                if (nodeType == "bm")
                {
                    this.rtFailInfo.Text = "正在同步" + name + "下人员信息" + Environment.NewLine;
                    user = db.View_UserInfo.ToList().Where(a => a.DEPT_id == groupID).Where(a => a.DEPT_id != 320).ToList();
                }

                new Thread(new ThreadStart(delegate
               {

                   int count = user.Count();
                   DBHelperEX dbHelper = new DBHelperEX();
                   int id = 1;
                   int failID = 0;
                   foreach (var item in user)
                   {
                       SetTextMessage(100 * id / count);
                       id++;
                       string sex = item.XB == null ? "男" : item.XB;
                       string photoPath = item.ZP == null ? "" : item.ZP;
                       if (photoPath == "" || !item.ZP.ToString().Contains("ftp"))
                       {
                           failID++;
                           rtFailInfo.Invoke(new Action(() =>
                           {
                               rtFailInfo.Text += "姓名" + item.ZSXM + "无相片路径不予同步" + Environment.NewLine;

                           }));
                           continue;

                       }
                       var userCount = user.Where(a => a.rybh == item.rybh).ToArray();
                       if (userCount.Length > 1)
                       {
                           failID++;
                           rtFailInfo.Invoke(new Action(() =>
                           {
                               rtFailInfo.Text += "姓名：" + item.ZSXM  +"人员编号:"+item.rybh.ToString() + "重复个数" + userCount.Length + Environment.NewLine;

                           }));
                       }
                       int supNum = photoPath.LastIndexOf("ftp") + 4;  //最后一个出现 在加上ftp/
                       photoPath = photoPath.Substring(supNum, photoPath.Length - supNum);
                       int userImginfo = photoPath.IndexOf("/") + 1;
                       string imgName = photoPath.Substring(userImginfo, photoPath.Length - userImginfo);
                       string kkzp = FileTran.DownloadFile(SPicUtils.path, imgName, photoPath);
                       string platName = SPicUtils.path + imgName;
                       string photoName = "";
                       CallProc call = new CallProc();
                       if (File.Exists(platName))//
                       {                           
                           photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 1, sex, item.sfzh.ToString(), 0, item.DEPT_id.ToString());
                           if (!string.IsNullOrWhiteSpace(photoName))
                           {
                               //scm平台照片存放文件夹命名方式为人员序号除以1000
                               int folderName = int.Parse(photoName.Substring(0, photoName.Length - 4)) / 1000;
                               if (!Directory.Exists(SPicUtils.path + folderName))
                               {
                                   Directory.CreateDirectory(SPicUtils.path + folderName);
                               }
                               string scmphotoName = SPicUtils.path + folderName + "\\" + photoName;
                               string tmpImgPath =  AppDomain.CurrentDomain.BaseDirectory + imgName;  //用于存放临时图片
                               //裁减图片原图片为平台原始图片,保存在scm平台根目录,因后面要压缩 故没有放在对应文件夹中
                               imgUtils.CutForCustom(SPicUtils.path + imgName, tmpImgPath, 140, 194, 0);
                               //压缩图片  原图片在scm平台图片根目录,压缩后图片在人员序号/1000的文件夹中，长,宽，质量
                               Common.CommonImg.CompressImage(tmpImgPath, scmphotoName, 194, 140, 60);
                               //imgUtils.GetReducedImage(exportPath + imgName, scmphotoName, 140, 194, 0);

                               //删除根目录图片
                               File.Delete(tmpImgPath);
                               FileInfo scmphoto = new FileInfo(scmphotoName);
                               FileTran.SaveFile(scmphoto, photoName, folderName.ToString()+"/", 10086);
                           }
                           else
                           {

                           }
                       }
                       else
                       {
                           failID++;
                           this.Invoke((MethodInvoker)delegate
                           {
                               if (item.rybh != null && item.sfzh != null)
                               {
                                   //照片不存在进行同步
                                   photoName = call.UserEx(item.rybh.ToString(), item.ZSXM.ToString(), 0, sex, item.sfzh.ToString(), 0, item.DEPT_id.ToString());


                                   string log = string.Format("姓名:{0}身份证{1}无照片或者照片不匹配照片名:{2}" + Environment.NewLine, item.ZSXM, item.sfzh, imgName);
                                   this.rtFailInfo.Text += log + Environment.NewLine; ;
                                   Log.WriteInfo(log);

                               }
                               else
                               {

                                   this.rtFailInfo.Text += item.ZSXM + "无人员编号" + Environment.NewLine; ;

                               }
                           });
                       }

                   }
                   rtFailInfo.Invoke(new Action(() =>
                   {
                       rtFailInfo.Text += "同步" + name + "下人员信息成功" + Environment.NewLine;
                       rtFailInfo.Text += "共" + count + "条信息,其中同步成功" + (count - failID) + "条信息" + Environment.NewLine;
                   }));
               }

                 )).Start();
            }
        }




        private void InitTree()
        {
            DataTable group_tb = group.GetDataBy_sjjg(0);
            for (int g = 0; g < group_tb.Rows.Count; g++)
            {
                TreeNode tn = new TreeNode();
                tn = treeView1.Nodes.Add(group_tb.Rows[g]["JGNAME"].ToString());
                tn.Text = group_tb.Rows[g]["jc"].ToString();
                tn.Tag = -1;
                tn.ToolTipText = "jg";
                tn.ImageIndex = 0;
                tn.SelectedImageIndex = 0;
                //  tn.Checked = true;
                //addJGTree(tn.Tag.ToString(), tn);
                addBMTree(group_tb.Rows[g]["GRPUP_ID"].ToString(), "0", tn);
            }
            //外协单位
            TreeNode tn1 = new TreeNode();
            tn1 = treeView1.Nodes.Add("外协单位");
            tn1.Text = "外协单位";
            tn1.Tag = "0";
            tn1.ToolTipText = "jg";
            tn1.ImageIndex = 0;
            tn1.SelectedImageIndex = 0;
            tn1.Checked = true;
            addJGTree(group_tb.Rows[0]["GRPUP_ID"].ToString(), tn1);
            //  treeView1.Nodes[0].ExpandAll();
            //   treeView1.SelectedNode = treeView1.Nodes[0].NextVisibleNode;
        }



        /// <summary>
        /// 递归加载addJGTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addJGTree(string fatherid, TreeNode pnode)
        {
            DataTable dt = group.GetDataBy_sjjg(int.Parse(fatherid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJJG] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "jg";
                    treeView1.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["jc"].ToString();
                    node.Tag = drv["GRPUP_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "jg";
                    pnode.Nodes.Add(node);
                    addJGTree(drv["GRPUP_ID"].ToString(), node);//递归  该节点加载子节点

                }
            }
        }

        /// <summary>
        /// 递归加载addBMTree列表
        /// </summary>
        /// <param name="fatherid">节点的fatherid</param>
        /// <param name="pnode">该节点</param>
        private void addBMTree(string jgid, string fatherid, TreeNode pnode)
        {
            DataTable dt = bm.GetDataBy_grpup_id(int.Parse(jgid));
            DataView dvTree = new DataView(dt);
            dvTree.RowFilter = "[SJBM] = " + fatherid;
            foreach (DataRowView drv in dvTree)
            {
                TreeNode node = new TreeNode();
                node.ImageIndex = 1;
                node.SelectedImageIndex = 3;
                if (pnode == null)
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();    //作为节点标识符
                    node.ToolTipText = "bm";
                    treeView1.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
                else
                {
                    node.Text = drv["BMMC"].ToString();
                    node.Tag = drv["DEPT_ID"].ToString();//作为节点标识符
                    node.ToolTipText = "bm";
                    pnode.Nodes.Add(node);
                    addBMTree(jgid, drv["DEPT_ID"].ToString(), node);//递归  该节点加载子节点
                }
            }
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                int id = int.Parse(e.Node.Tag.ToString());
                this.txtSynPerson.Text = e.Node.Text;
            }
        }



    }
}
